using System;
using System.Collections.Generic;
using System.Linq;
using GZ.DB.Entity.wcs_hy;
using GZ.DB.IRepository.wcs_hy;
using GZ.DB.Repository.wcs_hy;
using GZ.Common.Data;

namespace GZ.Projects.WCS_YB
{
	/// <summary>
	/// 双叉堆垛机处理结果
	/// </summary>
	public class DoubleStackerResult
	{
		public bool Success { get; set; }
		public string Message { get; set; }
	}

	public class DoubleStackerHandle
	{
		private const string LAST_TASK_TYPE_REDIS_KEY = "MEM.TC01_LastTaskType"; // Redis中记录上次执行任务类型的键

		/// <summary>
		/// 从Redis获取上次执行的任务类型
		/// </summary>
		private string GetLastExecutedTaskType()
		{
			try
			{
				string lastType = Conn.YBRedis.GetValue(LAST_TASK_TYPE_REDIS_KEY);
				return string.IsNullOrEmpty(lastType) ? "" : lastType;
			}
			catch (Exception ex)
			{
				Conn.YBLog.Error(1, "获取上次执行任务类型失败", 1, ex.ToString());
				return "";
			}
		}

		/// <summary>
		/// 保存上次执行的任务类型到Redis
		/// </summary>
		private bool SetLastExecutedTaskType(string taskType)
		{
			try
			{
				return Conn.YBRedis.SetValue(LAST_TASK_TYPE_REDIS_KEY, taskType, "MEMQueue");
			}
			catch (Exception ex)
			{
				Conn.YBLog.Error(1, "保存上次执行任务类型失败", 1, ex.ToString());
				return false;
			}
		}

		/// <summary>
		/// 统一的任务处理方法 - 按时间排序，一入一出交替执行
		/// </summary>
		public DoubleStackerResult ProcessTasksByTimeOrder(IEnumerable<StackerTaskEntity> allTasks)
		{
			string msg = "开始按时间顺序处理任务";
			bool Success = true;

			try
			{
				// 首先检查堆垛机状态
				var deviceStatus = CheckStackerStatus();
				if (!deviceStatus.Success)
				{
					return new DoubleStackerResult { Success = false, Message = msg + "\r\n\t" + deviceStatus.Message };
				}
				msg += "\r\n\t" + deviceStatus.Message;

				// 按时间排序所有任务
				var sortedTasks = allTasks.OrderBy(t => t.CreateTime).ToList();
				msg += $"\r\n\t发现 {sortedTasks.Count} 条待处理任务，按创建时间排序";

				// 从Redis获取上次执行的任务类型
				string lastExecutedTaskType = GetLastExecutedTaskType();
				msg += $"\r\n\t从Redis获取上次执行任务类型: [{lastExecutedTaskType}]";

				// 根据上次执行的任务类型决定优先级
				DoubleStackerResult result = null;
				bool taskExecuted = false;

				if (lastExecutedTaskType == "In")
				{
					// 上次执行了入库，优先尝试出库
					msg += "\r\n\t上次执行了入库任务，优先尝试出库任务";
					result = TryProcessOutboundTasks(sortedTasks);
					if (result.Success && result.Message.Contains("执行出库任务成功"))
					{
						// 任务类型已在MEM记录中一起更新，无需单独调用SetLastExecutedTaskType
						return new DoubleStackerResult { Success = true, Message = msg + "\r\n\t" + result.Message };
					}
					msg += "\r\n\t" + result.Message;

					// 如果没有出库任务可执行，继续尝试入库任务
					msg += "\r\n\t没有可执行的出库任务，继续尝试入库任务";
					result = TryProcessInboundTasks(sortedTasks);
					if (result.Success && result.Message.Contains("执行入库任务成功"))
					{
						return new DoubleStackerResult { Success = true, Message = msg + "\r\n\t" + result.Message };
					}
					msg += "\r\n\t" + result.Message;
				}
				else if (lastExecutedTaskType == "Out")
				{
					// 上次执行了出库，优先尝试入库
					msg += "\r\n\t上次执行了出库任务，优先尝试入库任务";
					result = TryProcessInboundTasks(sortedTasks);
					if (result.Success && result.Message.Contains("执行入库任务成功"))
					{
						return new DoubleStackerResult { Success = true, Message = msg + "\r\n\t" + result.Message };
					}
					msg += "\r\n\t" + result.Message;

					// 如果没有入库任务可执行，继续尝试出库任务
					msg += "\r\n\t没有可执行的入库任务，继续尝试出库任务";
					result = TryProcessOutboundTasks(sortedTasks);
					if (result.Success && result.Message.Contains("执行出库任务成功"))
					{
						return new DoubleStackerResult { Success = true, Message = msg + "\r\n\t" + result.Message };
					}
					msg += "\r\n\t" + result.Message;
				}

				// 如果优先级处理没有执行任务，按时间顺序找第一个可执行的任务
				msg += "\r\n\t优先级处理未执行任务，按时间顺序查找可执行任务";
				foreach (var task in sortedTasks)
				{
					msg += $"\r\n\t检查任务[{task.TaskNo}]，类型[{task.TaskType}]，创建时间[{task.CreateTime:yyyy-MM-dd HH:mm:ss}]";

					switch (task.TaskType)
					{
						case "ST_Out":
							result = ProcessOutboundTask(task, sortedTasks);
							if (result.Success)
							{
								return new DoubleStackerResult { Success = true, Message = msg + "\r\n\t" + result.Message };
							}
							break;

						case "ST_In":
							result = ProcessSingleInboundTask(task, sortedTasks);
							if (result.Success)
							{
								return new DoubleStackerResult { Success = true, Message = msg + "\r\n\t" + result.Message };
							}
							break;

						case "ST_Move":
							result = ProcessMoveTask(task);
							if (result.Success && result.Message.Contains("执行移库任务成功"))
							{
								// 移库任务单独记录任务类型（没有MEM数据）
								SetLastExecutedTaskType("Move");
								return new DoubleStackerResult { Success = true, Message = msg + "\r\n\t" + result.Message };
							}
							break;
					}

					// 如果当前任务不能执行，继续检查下一个任务
					if (result != null)
					{
						msg += "\r\n\t" + result.Message;
					}
				}

				msg += "\r\n\t完成任务处理流程，未执行任何任务";
				return new DoubleStackerResult { Success = true, Message = msg };
			}
			catch (Exception ex)
			{
				msg += $"\r\n\t任务处理异常: {ex.Message}";
				Conn.YBLog.Error(1, "1号堆垛机任务处理异常", 1, ex.ToString());
				return new DoubleStackerResult { Success = false, Message = msg };
			}
		}

		/// <summary>
		/// 检查堆垛机状态
		/// </summary>
		private DoubleStackerResult CheckStackerStatus()
		{
			try
			{
				string suffixName = "TC01";
				TaskDispatchHelper helper = new TaskDispatchHelper();
				var deviceStatus = helper.CheckDeviceStatus(suffixName,true); //true代表双工位状态查询

				if (!deviceStatus.IsReady)
				{
					return new DoubleStackerResult
					{
						Success = false,
						Message = $"1号堆垛机状态不满足：{deviceStatus.StatusMessage}"
					};
				}

				// 检查是否有未完成的任务
				IStackerTaskRepository stackerRepo = new StackerTaskRepository();
				var unfinishedTask = stackerRepo.FindList(t =>
					t.TaskState != "Create"
					&& t.DeviceNo == suffixName)
					.OrderByDescending(t => t.CreateTime)
					.FirstOrDefault();

				if (unfinishedTask != null)
				{
					return new DoubleStackerResult
					{
						Success = false,
						Message = $"1号堆垛机有未完成的任务[{unfinishedTask.TaskNo}]，跳过任务下发"
					};
				}

				return new DoubleStackerResult
				{
					Success = true,
					Message = "1号堆垛机状态检查通过，可以下发任务"
				};
			}
			catch (Exception ex)
			{
				return new DoubleStackerResult
				{
					Success = false,
					Message = $"检查堆垛机状态异常：{ex.Message}"
				};
			}
		}

		/// <summary>
		/// 尝试处理出库任务（优先级处理）
		/// </summary>
		private DoubleStackerResult TryProcessOutboundTasks(List<StackerTaskEntity> sortedTasks)
		{
			string msg = "尝试处理出库任务";

			var outboundTasks = sortedTasks.Where(t => t.TaskType == "ST_Out").ToList();
			if (!outboundTasks.Any())
			{
				return new DoubleStackerResult { Success = true, Message = msg + "\r\n\t未发现出库任务" };
			}

			// 按时间顺序尝试第一个可执行的出库任务
			foreach (var task in outboundTasks)
			{
				var result = ProcessOutboundTask(task, sortedTasks);
				if (result.Success)
				{
					// 找到并执行了一个出库任务，立即返回
					return new DoubleStackerResult { Success = true, Message = msg + "\r\n\t" + result.Message };
				}
				// 如果当前任务不能执行，记录信息但继续尝试下一个
				msg += "\r\n\t" + result.Message;
			}

			return new DoubleStackerResult { Success = true, Message = msg + "\r\n\t未找到可执行的出库任务" };
		}

		/// <summary>
		/// 尝试处理入库任务（优先级处理）
		/// </summary>
		private DoubleStackerResult TryProcessInboundTasks(List<StackerTaskEntity> sortedTasks)
		{
			string msg = "尝试处理入库任务";

			var inboundTasks = sortedTasks.Where(t => t.TaskType == "ST_In").ToList();
			if (!inboundTasks.Any())
			{
				return new DoubleStackerResult { Success = true, Message = msg + "\r\n\t未发现入库任务" };
			}

			// 按时间顺序尝试第一个可执行的入库任务
			foreach (var task in inboundTasks)
			{
				var result = ProcessSingleInboundTask(task, sortedTasks);
				if (result.Success && result.Message.Contains("执行入库任务成功"))
				{
					// 找到并执行了一个入库任务，立即返回
					return new DoubleStackerResult { Success = true, Message = msg + "\r\n\t" + result.Message };
				}
				// 如果当前任务不能执行，记录信息但继续尝试下一个
				msg += "\r\n\t" + result.Message;
			}

			return new DoubleStackerResult { Success = true, Message = msg + "\r\n\t未找到可执行的入库任务" };
		}

		/// <summary>
		/// 处理出库任务,找刚刚出库任务的同组任务
		/// </summary>
		private DoubleStackerResult ProcessOutboundTask(StackerTaskEntity task, List<StackerTaskEntity> allTasks)
		{
			string msg = $"处理出库任务[{task.TaskNo}]";

			try
			{
				// 检查是否是一组的任务
				if (string.IsNullOrEmpty(task.GroupNo))
				{
					return new DoubleStackerResult { Success = true, Message = msg + "\r\n\t出库任务无组号，跳过" };
				}

				// 查找同组的另一个任务
				var groupTasks = allTasks.Where(t =>
					t.TaskType == "ST_Out" &&
					t.GroupNo == task.GroupNo &&
					((t.ToLocalNo == "10100101" || t.ToLocalNo == "10100201") ||
					 (t.ToLocalNo == "20100101" || t.ToLocalNo == "20100201"))).ToList();

				if (groupTasks.Count < 2)
				{
					return new DoubleStackerResult { Success = true, Message = msg + $"\r\n\t组号[{task.GroupNo}]的任务数量不足2个，跳过" };
				}

				if (groupTasks.Count > 2)
				{
					return new DoubleStackerResult { Success = true, Message = msg + $"\r\n\t组号[{task.GroupNo}]的任务数量超过2个，跳过" };
				}

				// 检查出库口状态
				string redisKey = "";
				if (task.ToLocalNo.StartsWith("10"))
				{
					redisKey = $"LXPLC_1.PLC_STATE_{task.ToLocalNo}";
					msg += "\r\n\t检查一楼出库口状态";
				}
				else if (task.ToLocalNo.StartsWith("20"))
				{
					redisKey = $"LXPLC_2.PLC_STATE_{task.ToLocalNo}";
					msg += "\r\n\t检查二楼出库口状态";
				}
				else
				{
					return new DoubleStackerResult { Success = true, Message = msg + "\r\n\t无法识别出库口位置，跳过" };
				}

				string outPutValue = null;
				try
				{
					outPutValue = Conn.YBRedis.GetValue(redisKey);
				}
				catch (Exception redisEx)
				{
					return new DoubleStackerResult { Success = false, Message = msg + $"\r\n\t获取出库口Redis状态失败: {redisEx.Message}" };
				}

				if (outPutValue != "1")
				{
					return new DoubleStackerResult { Success = true, Message = msg + $"\r\n\t出库口状态为[{outPutValue}]，不满足执行条件" };
				}

				msg += "\r\n\t出库口状态检查通过，开始执行出库任务";
				var executeResult = ExecuteOutboundTasks(groupTasks);
				return new DoubleStackerResult { Success = executeResult.Success, Message = msg + "\r\n\t" + executeResult.Message };
			}
			catch (Exception ex)
			{
				msg += $"\r\n\t处理出库任务异常: {ex.Message}";
				return new DoubleStackerResult { Success = false, Message = msg };
			}
		}

		/// <summary>
		/// 处理单个入库任务
		/// </summary>
		private DoubleStackerResult ProcessSingleInboundTask(StackerTaskEntity task, List<StackerTaskEntity> allTasks)
		{
			string msg = $"处理入库任务[{task.TaskNo}]";

			try
			{
				// 检查入库口条码
				string barcodeRedisKey = "";
				if (task.FromLocalNo == "10100101" || task.FromLocalNo == "10100101")
				{
					barcodeRedisKey = $"LXPLC_1.{task.FromLocalNo}_BARCODE";
					msg += $"\r\n\t检查一楼入库口[{task.FromLocalNo}]条码";
				}
				else if (task.FromLocalNo == "20100101" || task.FromLocalNo == "20100101")
				{
					barcodeRedisKey = $"LXPLC_2.{task.FromLocalNo}_BARCODE";
					msg += $"\r\n\t检查二楼入库口[{task.FromLocalNo}]条码";
				}
				else
				{
					return new DoubleStackerResult { Success = true, Message = msg + "\r\n\t无法识别入库口位置，跳过" };
				}

				string barcodeValue = null;
				try
				{
					barcodeValue = Conn.YBRedis.GetValue(barcodeRedisKey);
				}
				catch (Exception redisEx)
				{
					return new DoubleStackerResult { Success = false, Message = msg + $"\r\n\t获取入库口条码失败: {redisEx.Message}" };
				}

				if (string.IsNullOrEmpty(barcodeValue) || barcodeValue != task.TrayCode)
				{
					return new DoubleStackerResult { Success = true, Message = msg + $"\r\n\t入库口条码[{barcodeValue}]与任务条码[{task.TrayCode}]不匹配，跳过" };
				}

				// 检查是否有配对任务（双叉入库）
				var pairedTask = GetPairedInboundTask(task, allTasks);
				if (pairedTask != null)
				{
					msg += $"\r\n\t发现配对任务[{pairedTask.TaskNo}]，执行双叉入库";
					var executeResult = ExecuteInboundTasks(new List<StackerTaskEntity> { task, pairedTask });
					return new DoubleStackerResult { Success = executeResult.Success, Message = msg + "\r\n\t" + executeResult.Message };
				}

				// 检查单任务是否等待超过5分钟
				double waitMinutes = (DateTime.Now - task.CreateTime).TotalMinutes;
				msg += $"\r\n\t单任务已等待 {waitMinutes:F1} 分钟";

				if (waitMinutes > 5)
				{
					msg += "\r\n\t等待超过5分钟，执行单叉入库";
					var executeResult = ExecuteInboundTasks(new List<StackerTaskEntity> { task });
					return new DoubleStackerResult { Success = executeResult.Success, Message = msg + "\r\n\t" + executeResult.Message };
				}
				else
				{
					return new DoubleStackerResult { Success = true, Message = msg + "\r\n\t等待未超过5分钟，继续等待" };
				}
			}
			catch (Exception ex)
			{
				msg += $"\r\n\t处理入库任务异常: {ex.Message}";
				return new DoubleStackerResult { Success = false, Message = msg };
			}
		}

		/// <summary>
		/// 获取配对的入库任务
		/// </summary>
		private StackerTaskEntity GetPairedInboundTask(StackerTaskEntity task, List<StackerTaskEntity> allTasks)
		{
			string pairedFromLocalNo = "";

			if (task.FromLocalNo == "10102801")
				pairedFromLocalNo = "10103001";
			else if (task.FromLocalNo == "10103001")
				pairedFromLocalNo = "10102801";
			else if (task.FromLocalNo == "20100101")
				pairedFromLocalNo = "20100201";
			else if (task.FromLocalNo == "20100201")
				pairedFromLocalNo = "20100101";
			else
				return null;

			return allTasks.FirstOrDefault(t =>
				t.TaskType == "ST_In" &&
				t.FromLocalNo == pairedFromLocalNo &&
				t.TaskState == "Create");
		}

		/// <summary>
		/// 处理移库任务
		/// </summary>
		private DoubleStackerResult ProcessMoveTask(StackerTaskEntity task)
		{
			string msg = $"处理移库任务[{task.TaskNo}]";

			try
			{
				msg += "\r\n\t移库任务直接执行";
				TaskDispatchHelper helper = new TaskDispatchHelper();
				bool result = helper.TaskSend_Move(task, out string moveMsg);

				return new DoubleStackerResult
				{
					Success = result,
					Message = msg + "\r\n\t" + moveMsg + (result ? "\r\n\t执行移库任务成功" : "")
				};
			}
			catch (Exception ex)
			{
				msg += $"\r\n\t处理移库任务异常: {ex.Message}";
				return new DoubleStackerResult { Success = false, Message = msg };
			}
		}

		private DoubleStackerResult ExecuteOutboundTasks(List<StackerTaskEntity> tasks)
		{
			string msg = $"开始执行出库任务，任务数: {tasks.Count}，组号: {tasks[0].GroupNo}";
			bool Success = false;

			try
			{
				// 遍历他的任务信息，找出叉1 和 叉2的fromX fromY fromZ toX toY toZ等信息
				var fork1Task = tasks[0];
				var fork2Task = tasks[1];

				msg += $"\r\n\t叉1坐标: 起点({fork1Task.FromX},{fork1Task.FromY},{fork1Task.FromZ}) 终点({fork1Task.ToX},{fork1Task.ToY},{fork1Task.ToZ})";
				msg += $"\r\n\t叉2坐标: 起点({fork2Task.FromX},{fork2Task.FromY},{fork2Task.FromZ}) 终点({fork2Task.ToX},{fork2Task.ToY},{fork2Task.ToZ})";

				// 发送任务到Redis
				StackerSendToRedis stackerSendToRedis = new StackerSendToRedis();
				bool result = stackerSendToRedis.SendTask_DoubleStation(fork1Task, fork2Task, out string redisMsg);

				msg += "\r\n\t调用堆垛机控制系统执行出库操作,更新任务状态";

				if (result)
				{
					// 更新任务状态
					using (var db = new RepositoryBase().BeginTrans())
					{
						foreach (var task in tasks)
						{
							task.TaskState = "Send"; // 更新任务状态为已发送
							task.TaskStartTime = DateTime.Now;
							task.LastUpdatedTime = DateTime.Now;
							db.Update(task);
							msg += $"\r\n\t更新任务 {task.TrayCode} 状态为 Send，起点: {task.FromLocalNo}，终点: {task.ToLocalNo}";
						}

						int dbResult = db.Commit();
						if (dbResult < 1)
						{
							msg += "\r\n\t事务提交失败，更新任务状态未成功";
							Success = false;
						}
						else
						{
							// 记录双叉出库任务的MEM数据，同时记录任务类型
							bool memResult = StackMemTaskInfo(
								fork1Task.DeviceTaskNo, fork1Task.TrayCode,
								$"{fork1Task.FromX:D2}{fork1Task.FromY:D2}{fork1Task.FromZ:D2}",
								$"{fork1Task.ToX:D2}{fork1Task.ToY:D2}{fork1Task.ToZ:D2}",
								fork2Task.DeviceTaskNo, fork2Task.TrayCode,
								$"{fork2Task.FromX:D2}{fork2Task.FromY:D2}{fork2Task.FromZ:D2}",
								$"{fork2Task.ToX:D2}{fork2Task.ToY:D2}{fork2Task.ToZ:D2}",
								"01", "Out");

							if (memResult)
							{
								msg += $"\r\n\t双叉出库任务MEM数据记录成功";
							}
							else
							{
								msg += $"\r\n\t双叉出库任务MEM数据记录失败";
							}

							msg += $"\r\n\t1号堆垛机执行出库任务成功，组号: {tasks[0].GroupNo}, 任务数: {tasks.Count}";
							Success = true;
						}
					}
				}
				else
				{
					msg += $"\r\n\t发送任务到Redis失败: {redisMsg}";
					Success = false;
				}
			}
			catch (Exception ex)
			{
				msg += $"\r\n\t执行出库任务异常: {ex.Message}";
				Conn.YBLog.Error(1, "执行出库任务异常", 1, ex.ToString());
				Success = false;
			}

			return new DoubleStackerResult { Success = Success, Message = msg };
		}

		private DoubleStackerResult ExecuteInboundTasks(List<StackerTaskEntity> tasks)
		{
			string msg = $"开始执行入库任务，任务数: {tasks.Count}";
			bool Success = false;

			try
			{
				if (tasks.Count == 2)
				{
					// 两个插齿都有任务，双任务执行
					msg += "\r\n\t执行双叉入库操作";

					// 遍历他的任务信息，分别找出叉1 和 叉2的fromX fromY fromZ toX toY toZ等信息
					//确定里外哪个是叉1 哪个是叉2
					var fork1Task = tasks.FirstOrDefault(t => t.FromLocalNo == "10102801" || t.FromLocalNo == "INGET1_R2_1");
					var fork2Task = tasks.FirstOrDefault(t => t.FromLocalNo == "10103001" || t.FromLocalNo == "INGET1_R2_2");

					if (fork1Task != null && fork2Task != null)
					{
						msg += $"\r\n\t叉1坐标: 起点({fork1Task.FromX},{fork1Task.FromY},{fork1Task.FromZ}) 终点({fork1Task.ToX},{fork1Task.ToY},{fork1Task.ToZ})";
						msg += $"\r\n\t叉2坐标: 起点({fork2Task.FromX},{fork2Task.FromY},{fork2Task.FromZ}) 终点({fork2Task.ToX},{fork2Task.ToY},{fork2Task.ToZ})";

						// 发送任务到Redis
						StackerSendToRedis stackerSendToRedis = new StackerSendToRedis();
						bool result = stackerSendToRedis.SendTask_DoubleStation(fork1Task, fork2Task, out string redisMsg);

						msg += "\r\n\t调用堆垛机控制系统执行双叉入库操作";

						if (result)
						{
							// 更新任务状态
							using (var db = new RepositoryBase().BeginTrans())
							{
								foreach (var task in tasks)
								{
									task.TaskState = "Send"; // 更新任务状态为已发送
									db.Update(task);
									
									//上报wms
									if (task.TaskType == "ST_Out" || task.TaskType == "ST_Move")
									{
										//todo 接口上报任务状态
										SystemSynchronizationEntity systemSynchronization = new SystemSynchronizationEntity();
										systemSynchronization.syn_direction = 1;
										systemSynchronization.syn_status = 0;
										systemSynchronization.ope_type = "1";
										systemSynchronization.task_no = task.TaskNo;
										systemSynchronization.ope_time = DateTime.Now;
										db.Insert(systemSynchronization);
										msg += $"\r\n\t上报WMS任务状态，任务号: {task.TaskNo}，操作类型: {systemSynchronization.ope_type}";
									}
									msg += $"\r\n\t更新任务 {task.TrayCode} 状态为 Send，起点: {task.FromLocalNo}，终点: {task.ToLocalNo}";
								}

								int dbResult = db.Commit();
								if (dbResult < 1)
								{
									msg += "\r\n\t事务提交失败，更新任务状态未成功";
									Success = false;
								}
								else
								{
									// 记录双叉入库任务的MEM数据，同时记录任务类型
									bool memResult = StackMemTaskInfo(
										fork1Task.DeviceTaskNo, fork1Task.TrayCode,
										$"{fork1Task.FromX:D2}{fork1Task.FromY:D2}{fork1Task.FromZ:D2}",
										$"{fork1Task.ToX:D2}{fork1Task.ToY:D2}{fork1Task.ToZ:D2}",
										fork2Task.DeviceTaskNo, fork2Task.TrayCode,
										$"{fork2Task.FromX:D2}{fork2Task.FromY:D2}{fork2Task.FromZ:D2}",
										$"{fork2Task.ToX:D2}{fork2Task.ToY:D2}{fork2Task.ToZ:D2}",
										"01", "In");

									if (memResult)
									{
										msg += $"\r\n\t双叉入库任务MEM数据记录成功";
									}
									else
									{
										msg += $"\r\n\t双叉入库任务MEM数据记录失败";
									}

									msg += $"\r\n\t1号堆垛机执行双叉入库任务成功，站台: {fork1Task.FromLocalNo} 和 {fork2Task.FromLocalNo}, 任务数: {tasks.Count}";
									Success = true;
								}
							}
						}
						else
						{
							msg += $"\r\n\t发送双叉任务到Redis失败: {redisMsg}";
							Success = false;
						}
					}
					else
					{
						msg += "\r\n\t无法正确识别叉1和叉2的任务，任务执行失败";
						Conn.YBLog.Error(1, "堆垛机处理", 1, msg);
						Success = false;
					}
				}
				else if (tasks.Count == 1)
				{
					// 单任务执行（超时情况）
					var singleTask = tasks[0];
					msg += $"\r\n\t执行单叉入库操作，站台: {singleTask.FromLocalNo}, 任务创建时间: {singleTask.CreateTime}";
					msg += $"\r\n\t单叉坐标: 起点({singleTask.FromX},{singleTask.FromY},{singleTask.FromZ}) 终点({singleTask.ToX},{singleTask.ToY},{singleTask.ToZ})";

					// 发送单任务到Redis
					StackerSendToRedis stackerSendToRedis = new StackerSendToRedis();
					bool result = stackerSendToRedis.SendTask_SingleStation("1", singleTask, out string redisMsg);

					msg += "\r\n\t调用堆垛机控制系统执行单叉入库操作";

					if (result)
					{
						// 更新任务状态
						using (var db = new RepositoryBase().BeginTrans())
						{
							singleTask.TaskState = "Send";
							db.Update(singleTask);
							msg += $"\r\n\t更新任务 {singleTask.TrayCode} 状态为 Send，起点: {singleTask.FromLocalNo}，终点: {singleTask.ToLocalNo}";

							int dbResult = db.Commit();
							if (dbResult < 1)
							{
								msg += "\r\n\t事务提交失败，更新任务状态未成功";
								Success = false;
							}
							else
							{
								// 记录单叉入库任务的MEM数据（只记录到叉1），同时记录任务类型
								bool memResult = StackMemTaskInfo(
									singleTask.DeviceTaskNo, singleTask.TrayCode,
									$"{singleTask.FromX:D2}{singleTask.FromY:D2}{singleTask.FromZ:D2}",
									$"{singleTask.ToX:D2}{singleTask.ToY:D2}{singleTask.ToZ:D2}",
									"", "", "", "",  // 叉2数据为空
									"01", "In");

								if (memResult)
								{
									msg += $"\r\n\t单叉入库任务MEM数据记录成功";
								}
								else
								{
									msg += $"\r\n\t单叉入库任务MEM数据记录失败";
								}

								msg += $"\r\n\t1号堆垛机执行单叉入库任务成功（超时），站台: {singleTask.FromLocalNo}, 任务创建时间: {singleTask.CreateTime}";
								Success = true;
							}
						}
					}
					else
					{
						msg += $"\r\n\t发送单叉任务到Redis失败: {redisMsg}";
						Success = false;
					}
				}
			}
			catch (Exception ex)
			{
				msg += $"\r\n\t执行入库任务异常: {ex.Message}";
				Conn.YBLog.Error(1, "执行入库任务异常", 1, ex.ToString());
				Success = false;
			}

			return new DoubleStackerResult { Success = Success, Message = msg };
		}
		/// <summary>
		/// 记录堆垛机任务的MEM数据到Redis，同时记录上次执行任务类型
		/// </summary>
		/// <param name="deviceTaskNo1">叉1设备任务号</param>
		/// <param name="contNum1">叉1托盘编码</param>
		/// <param name="curNum1">叉1当前位置</param>
		/// <param name="toNum1">叉1目标位置</param>
		/// <param name="deviceTaskNo2">叉2设备任务号（单叉时传空字符串）</param>
		/// <param name="contNum2">叉2托盘编码（单叉时传空字符串）</param>
		/// <param name="curNum2">叉2当前位置（单叉时传空字符串）</param>
		/// <param name="toNum2">叉2目标位置（单叉时传空字符串）</param>
		/// <param name="num">设备编号</param>
		/// <param name="taskType">任务类型</param>
		/// <returns>记录是否成功</returns>
		public bool StackMemTaskInfo(string deviceTaskNo1, string contNum1, string curNum1, string toNum1,
			string deviceTaskNo2, string contNum2, string curNum2, string toNum2,
			string num, string taskType)
		{
			try
			{
				string setQueue = "MEMQueue";
				string groupName = $"MEM.TC{num}_INFO";

				// 判断是单叉还是双叉任务
				bool isDoubleTask = !string.IsNullOrEmpty(deviceTaskNo2) && !string.IsNullOrEmpty(contNum2);
				string taskDescription = isDoubleTask ? "双叉" : "单叉";

				GZ.Modular.Redis.WriteGroupEntity group = new GZ.Modular.Redis.WriteGroupEntity
				{
					groupName = groupName,
					queueStatus = 1,
					queueTime = DateTime.Now,
					writeList = new List<GZ.Modular.Redis.ParamData>
					{
						// 叉1的数据（单叉和双叉都有）
						new GZ.Modular.Redis.ParamData { paramName = $"MEM.TC{num}_DeviceTaskNo1", paramValue = deviceTaskNo1 ?? "" },
						new GZ.Modular.Redis.ParamData { paramName = $"MEM.TC{num}_Cont1", paramValue = contNum1 ?? "" },
						new GZ.Modular.Redis.ParamData { paramName = $"MEM.TC{num}_CurPos1", paramValue = curNum1 ?? "" },
						new GZ.Modular.Redis.ParamData { paramName = $"MEM.TC{num}_ToPos1", paramValue = toNum1 ?? "" },

						// 叉2的数据（双叉时有值，单叉时为空）
						new GZ.Modular.Redis.ParamData { paramName = $"MEM.TC{num}_DeviceTaskNo2", paramValue = deviceTaskNo2 ?? "" },
						new GZ.Modular.Redis.ParamData { paramName = $"MEM.TC{num}_Cont2", paramValue = contNum2 ?? "" },
						new GZ.Modular.Redis.ParamData { paramName = $"MEM.TC{num}_CurPos2", paramValue = curNum2 ?? "" },
						new GZ.Modular.Redis.ParamData { paramName = $"MEM.TC{num}_ToPos2", paramValue = toNum2 ?? "" },

						// 记录上次执行的任务类型
						new GZ.Modular.Redis.ParamData { paramName = LAST_TASK_TYPE_REDIS_KEY, paramValue = taskType }
					}
				};

				bool result = Conn.YBRedis.SetQueue(group, setQueue, "", "");
				return result;
			}
			catch (Exception ex)
			{
				Conn.YBLog.Error(1, $"[{(string.IsNullOrEmpty(deviceTaskNo2) ? "单叉" : "双叉")}堆垛机MEM记录失败[TC{num}]]", 1, ex.ToString());
				return false;
			}
		}
	}
}